<html>
<head>
    <meta charset="UTF-8">
    <style>
        table
        {
            border-collapse:collapse;
        }
        th, td
        {
            border: 1px solid black;
            height: 40px;
            padding: 15px;
        }
    </style>
</head>
<body>
<center>
<h1>秒杀活动</h1>

<table>
    <tr>
        <th>商品</th>
        <th>价格</th>
        <th>库存</th>
    </tr>
    <tr>
        <td id="product"></td>
        <td id="price"></td>
        <td id="stock"></td>
    </tr>
</table>
    <div>
        <h3 id="notStart">

        </h3>
        <h3 id="starting">
            <button id="buy">秒杀</button>
        </h3>
    </div>

</center>
<script src="js/libs/jquery.js"></script>
<script>

function countDown(startTime) {
    let content = `活动将于${startTime.Format("yyyy-MM-dd hh:mm:ss")}开始<br>
    现在时间: ${new Date().Format("yyyy-MM-dd hh:mm:ss")}
    `;

    $("#notStart").html(content);

    setTimeout(() => {
        countDown(startTime);
    }, 1000);
}

$.get("/api/flashsale/init", (data, status) => {

    if (status === 'success') {
        console.log("初始化成功!");
        $.get("/api/flashsale/info", (data) => {
            console.log(data);
            $("#product").text(data.name);
            $("#price").text(data.price);
            $("#stock").text(data.stock);

            let startTime = new Date(data.startTime);

            if ((new Date()).getTime() < startTime.getTime()) {
                console.log("未开始");
                $("#notStart").show();
                $("#starting").hide();

                countDown(startTime);
            } else {
                console.log("开始了");
                $("#notStart").hide();
                $("#starting").show();
            }
        });
    }

});

function loadInfo() {
    $.get("/api/flashsale/info", (data) => {
        console.log(data);
        $("#product").text(data.name);
        $("#price").text(data.price);
        $("#stock").text(data.stock);
    });
}

$("#buy").click(() => {

    $.get('http://localhost:8080/api/flashsale/buy?userId=zhangsan', (data) => {
        if (data.status == 0) {
            alert(data.message);
            window.location.href = '/payment.html';
        } else {
            alert(data.message);
        }
        loadInfo();
    });
})


Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

</script>
</body>
</html>